package croppingplanap;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Point;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class LegendPanel extends JPanel{

	private CroppingPlan plan;
	
	private SortedSet<Crop> oldCropSet;
	private GridLayout layout;
	private JPanel panel;
	private CroppingPlanAp app;
	private Crop activeCrop;
	private Crop previousCrop;
	
	private boolean ready;
	
	public static final Color BGCOLOR = Color.white;
	
	public LegendPanel(CroppingPlanAp app, CroppingPlan plan){
		oldCropSet = null;
		activeCrop = null;
		previousCrop = null;
		
		this.setBackground(BGCOLOR);
		
		panel = new JPanel();
		this.plan = plan;
		layout = new GridLayout(1,1,1,1);
		panel.setLayout(layout);
		this.setBorder(BorderFactory.createTitledBorder("Legend"));
		this.add(panel);
		Dimension d = new Dimension(150, 400);
		
		this.setMinimumSize(d);
		this.setPreferredSize(d);
		this.refreshLegend();
		this.app = app;
		ready = false;
	}
	
	public LegendPanel(CroppingPlan plan, Crop firstCrop){
		this(null, plan);
	}
	
	public void setReady(){
		this.ready = true;
	}
	
	public void refreshLegend(){
		if(!ready) return;
		Crop currentCrop = null;
		SortedSet<Crop> currentCrops = new TreeSet<Crop>();
		currentCrops.add(activeCrop);
		int width = plan.getWidth();
		int height = plan.getHeight();
		Point p = new Point(0,0);
		for(p.x = 0; p.x < width; p.x++){
			for(p.y = 0; p.y < height; p.y++){
				currentCrop = plan.getCropAt(p);
				if(currentCrop != null && currentCrop != Crop.NOTHING) currentCrops.add(currentCrop);
			}
		}
		
		if(!currentCrops.equals(oldCropSet) || activeCrop != previousCrop){
			previousCrop = activeCrop;
			panel.removeAll();
			layout.setColumns(1);
			layout.setHgap(1);
			layout.setVgap(1);
			if(currentCrops.size() > 0){
				layout.setRows(currentCrops.size());
				for(Crop c : currentCrops){
					panel.add(new LegendEntry(c, activeCrop, app));
				}
			}else{
				//layout.setRows(1);
				//panel.add(new JLabel("[No Crops Plotted]"));
			}
			oldCropSet = currentCrops;
			if(app == null){
				this.validate();
				this.repaint();
			}else{
				app.validate();
				app.repaint();			
			}
		}		
	}
	
	public void setCrop(Crop newCrop){
		this.activeCrop = newCrop;
		this.refreshLegend();
	}
	
	
	
}
